import React, { useEffect, useRef, useState } from "react";
import "./TodoMain.css";
import { useDispatch, useSelector } from "react-redux";
import { asyncUpdateTodoTitle, todoSelector, updateTitle } from "../../../app/slices/todoSlice";
export default function TodoMain() {
  //获取状态
  let todos = useSelector(todoSelector);
  //声明状态
  let [isModifying, setIsModifying] = useState(false);
  let [mofifyId, setModifyId] = useState(null);
  //获取 dispatch 函数
  let dispatch = useDispatch();
  //创建 ref
  let input = useRef();

  useEffect(() => {
    //修改 input 元素的选中状态
    input.current?.focus(); // input.current && input.current.focus()
    input.current?.select();
  }, [mofifyId,isModifying])
  return (
    <ul className="todo-main">
      {todos.map((item) => (
        <li key={item.id}>
          <input type="checkbox" checked={item.done} onChange={() => {}} />
          
          {isModifying && item.id===mofifyId 
            ? <input type="text" 
                defaultValue={item.title}  
                ref={input}
                onBlur={(e) => {
                  //伪代码
                  // dispatch(updateTitle({id: item.id, title: 'xx'}))
                  // {type: 'todo/updateTitle', payload: {id: item.id, title: 'xx'}}
                  // dispatch(updateTitle({id: item.id, title: e.target.value}));
                  dispatch(asyncUpdateTodoTitle(item.id, e.target.value))
                  //更新状态
                  setIsModifying(false);

                }}
                />
            : <span onDoubleClick={() => {
              //更新状态
              setIsModifying(true);
              //更新修改任务的 id
              setModifyId(item.id);
            }}>{item.title}</span>
          }
          <button className="btn btn-danger">删除</button>
        </li>
      ))}
    </ul>
  );
}
